package com.metro.paperless.common.utils;

import java.io.Serializable;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionIdGenerator;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * 封装各种生成唯一性ID算法的工具类.
 * @author xk
 */
@Component
@Lazy(false)
public class IdGen implements SessionIdGenerator {

	private static SecureRandom random = new SecureRandom();
	
	/**
	 * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
	 */
	public static String uuid() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	
	/**
	 * 使用SecureRandom随机生成Long. 
	 */
	public static long randomLong() {
		return Math.abs(random.nextLong());
	}
	
	/**
	 * 短信随机码的生成范围
	 */
	private static String[]	beforeShuffle	= new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
	
	/**
	 * 生成短信验证码,随机数
	 * @param length
	 * @return
	 */
	public static String smscode(int length) {
		List<String> list = Arrays.asList(beforeShuffle);
		Collections.shuffle(list);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i));
		}

		String afterShuffle = sb.toString();
		String result = afterShuffle.substring(2, 2+length);
		return result;
	}
	
	/**
	 * 生成6位短信验证码,随机数
	 * @return
	 */
	public static String smscode() {
		return smscode(6);
	}
	
	/**
	 * 生成随机的编码
	 * 编号生成规则为 【年+月+日+四位随机数】  即18+03+04+1234（不可编辑、唯一），
	 * @return
	 */
	public static String getBarCode(){
		Date now = new Date();
        String code = String.valueOf(DateUtil.getYear(now)).substring(2, 4) +  DateUtil.getMonthStr(now) + DateUtil.getDayStr(now) + IdGen.smscode(4);
		return code;
	}

	/**
	 * Activiti ID 生成
	 */
	public String getNextId() {
        try {
            return String.valueOf(SequenceUtil.nextValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

	@Override
	public Serializable generateId(Session session) {
		return IdGen.uuid();
	}

}
